<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Collect extends CI_Controller
{
	private $user_data;
	function __construct()
	{
		parent::__construct();
        $this->load->config('layout', TRUE);
		$this->load->helper(array('form', 'url'));
		$this->load->library('security');
		$this->load->library('houseme_view');
		$this->load->library('facebook');
		$this->load->library('tank_auth');
		$this->load->library('form_validation');
		$this->load->database();
		$this->load->model('post_model');
		$this->load->model('topic_model');
		$this->load->model('user_model');
		$this->lang->load('houseme');
		$this->lang->load('tank_auth');
		$this->user_data = $this->session->all_userdata();//get session
	}

	function show_default_category(){
		$this->user_model->show_user_collect();
	}

	function index(){
		$uid = $this->uri->segment(2);
		$collect_category = $this->uri->segment(3);
		$collect_category = urldecode($collect_category);

		$data['category'] = $this->config->item('category', 'layout');
		$data['login_area'] = $this->load->view('houseme/login_area', '', true);
		
		$user_collects = $this->user_model->selectUserCollects($uid);
		
		$collects = $user_collects[0]['collects'];
		$collect_alias = $user_collects[0]['collect_alias'];
		$collects = urldecode($collects);
		$collects = json_decode($collects,true);
		$collect_alias = urldecode($collect_alias);
		$collect_alias = json_decode($collect_alias,true);

		//initial arrays
		$post_collected_id_string = array();
		$topic_collected_id_string = array();
		$share_collected_id_string = array();

		$collected_topic = array();
		$collected_post = array();
		$user_collected = array();
		//echo "<pre>";print_r($collects);echo "</pre>";exit;
		//$collect_category = $collect_alias[$collect_category];

		foreach ($collects[$collect_category] as $key => $collect_link) {
				
				if(strpos($collect_link, 'post') !== false){
					$temp = explode('/', $collect_link);
					$post_collected_id_string[] = $temp[3];
				}
				elseif(strpos($collect_link, 'share') !== false){
					$temp = explode('/', $collect_link);
					$share_collected_id_string[] = $temp[3];
				}
				elseif(strpos($collect_link, 'topic') !== false){
					$temp = explode('/', $collect_link);
					$topic_collected_id_string[] = $temp[3];
				}
			
		}

		if(!empty($topic_collected_id_string)){
			$collected_topic = $this->topic_model->get_topic_by_id_string($topic_collected_id_string);
		}

		if(!empty($post_collected_id_string)){
			$collected_post = $this->post_model->get_post_by_id_string($post_collected_id_string);	
		}

		$user_collected = array_merge($collected_post,$collected_topic);

		if(!empty($share_collected_id_string)){
			$collected_share = $this->post_model->get_share_by_id_string($share_collected_id_string);	
			$user_collected = array_merge($collected_share,$user_collected);
		}

				
		usort($user_collected, array('Collect','dateSort'));//sort post and topic array by datetime

		$data['user_collected'] = $user_collected;
		$this->load->view('houseme/collect_index', $data);

	}
	function add(){
		$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
		$user_data = $this->user_data;

		if(isset($user_data['user_data']['LOGIN_INFO']['id'])){
			$uid = $user_data['user_data']['LOGIN_INFO']['id'];
		}
		elseif(isset($user_data['fe_user_id'])){
			$uid = $user_data['fe_user_id'];
		}
		
		$user_collects = $this->user_model->selectUserCollects($uid);
		$collects = $user_collects[0]['collects'];
		$collects = urldecode($collects);
		$collects = json_decode($collects);
		$replace_array = array('/','(',')');
		$data['collect_category'] = str_replace($replace_array, '', $data['collect_category']);

		if(!isset($collects->$data['collect_category'])){
			$return['status_code'] = 2; // not find category in db
			$return['msg'] = '請選擇分類';
		}
		else{
			
			array_push($collects->$data['collect_category'], $data['collect_link']);
			$collects = json_encode($collects);
			$collects = urlencode($collects);
			if($this->user_model->updateUserCollects($uid,$collects)){
				$return['status_code'] = 1;
				$return['msg'] = '收藏成功！';
			}
			else{
				$return['status_code'] = 3; // not find category in db
				$return['msg'] = '收藏時發生錯誤，請連絡網站管理者或稍侯再試';
			}
		}
		echo json_encode($return);
	}

	function showForm(){
		$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
		if($this->facebook->checkLoginStatus() || $this->tank_auth->is_fe_logged_in()){//fb already login || email login

			$user_data = $this->user_data;
			if(isset($user_data['user_data']['LOGIN_INFO']['id'])){
				$uid = $user_data['user_data']['LOGIN_INFO']['id'];
			}
			elseif(isset($user_data['fe_user_id'])){
				$uid = $user_data['fe_user_id'];
			}

			if($user_collects = $this->user_model->selectUserCollects($uid)){
				$collects = $user_collects[0]['collect_alias'];
				$collects = urldecode($collects);
				$data['user_collects'] = json_decode($collects);

			}
			else{
				$data['user_collects'] = array();
			}
			
			if (strpos($data['collect_link'],'post') !== false) { // post 
			    $temp = explode('/', $data['collect_link']);
			    $id = $temp[3];
			    $post = $this->post_model->get_post_by_id($id);
			    $temp = json_decode($post[0]['upload_image']);
                $image_filename = $temp[0];
                $data['img_src'] = $this->config->item('image_uploader_thumbs','layout').'/'.$post[0]['user_id'].'/'.$image_filename;
			}
			elseif(strpos($data['collect_link'],'share') !== false){	// topic
				$temp = explode('/', $data['collect_link']);
			    $id = $temp[3];
			    $post = $this->post_model->get_share_by_id($id);
			    $temp = json_decode($post[0]['upload_image']);
                $image_filename = $temp[0];
                $data['img_src'] = $this->config->item('image_uploader_fe_thumbs','layout').'/'.$post[0]['user_id'].'/'.$image_filename;
			}
			elseif(strpos($data['collect_link'],'topic') !== false){	// topic
				$temp = explode('/', $data['collect_link']);
			    $id = $temp[3];
			    $topic = $this->topic_model->get_topic_by_id($id);
			    $doc = new DOMDocument();
                @$doc->loadHTML($topic[0]['topic_desc']);
                $first_img = $doc->getElementsByTagName('img')->item(0);
                $data['img_src'] = $first_img->attributes->getNamedItem("src")->value;
			}

			$return['status_code'] = 1; // insert successfully
			$return['html'] = $this->load->view('houseme/collect_form', $data, true);
		}
		else{ //fb not login
			$return['status_code'] = 3; // fb not login
			$return['msg'] = '請先登入';
		}

		echo json_encode($return);
	}

	function showEditCollectForm(){
		$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter

		if($this->facebook->checkLoginStatus() || $this->tank_auth->is_fe_logged_in()){//fb already login

			$return['status_code'] = 1; // login successfully
			$return['html'] = $this->load->view('houseme/edit_collect_form', $data, true);;
		}
		else{ //fb not login
			$return['status_code'] = 3; // fb not login
			$return['msg'] = '請先登入';
		}

		echo json_encode($return);
	}

	function showUploadIdeaForm(){

		$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter

		$page_action_event_element = array(
			'page_action_event_element'  => '.uploadShareBtn a'
		);

		$this->session->set_userdata($page_action_event_element);


		if($this->facebook->checkLoginStatus() || $this->tank_auth->is_fe_logged_in()){//fb already login
			$data['category'] = $this->config->item('category', 'layout');
			$return['status_code'] = 1; // login successfully

			if(empty($this->user_data['fe_username'])){
				$return['html'] = $this->load->view('houseme/upload_idea_form_with_name', $data, true);
			}	
			elseif(isset($this->user_data['user_data']['LOGIN_INFO']['name']) && empty($this->user_data['user_data']['LOGIN_INFO']['name'])){
				$return['html'] = $this->load->view('houseme/upload_idea_form_with_name', $data, true);
			}
			else{//不需要輸入名稱
				$return['html'] = $this->load->view('houseme/upload_idea_form', $data, true);
			}

			
		}
		else{ //fb not login
			$return['status_code'] = 3; // fb not login
			$return['msg'] = '請先登入';
		}

		echo json_encode($return);
	}

	function uploadIdea(){
		
		$data = array();
		$return = array();
		$user_data = $this->user_data;
		//echo "<pre>";print_r($user_data);echo "</pre>";exit;
		//echo "<pre>";print_r($_FILES);echo "</pre>";exit;
		$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
		$this->form_validation->set_rules('post_excerpt', 'post excerpt', 'trim|required|xss_clean');
		$this->form_validation->set_rules('post_desc', 'post desc', 'trim|required|xss_clean');

		if ($this->form_validation->run()) {

			if(!isset($_FILES['upload_image']['name'][0])){
				$return['status_code'] = 2;
				$return['msg'] = '請至少上傳一張圖片';
				$return['html'] = $this->load->view('houseme/upload_idea_form', $data, true);
				echo json_encode($return);exit;
				
			}
			else{
				$allowedTypes = $this->config->item('allow_upload_image_type', 'layout');

				foreach ($_FILES['upload_image']['tmp_name'] as $key => $value) {
					$detectedType = exif_imagetype($value);
					if(!in_array($detectedType, $allowedTypes)){
						$return['status_code'] = 2;
						$return['msg'] = '檔案只允許圖片格式';
						$return['html'] = $this->load->view('houseme/upload_idea_form', $data, true);
						echo json_encode($return);exit;
					}
				}

				// check file type success!
				// replace \r\n to <br >
				
				$data['post_desc'] = nl2br($data['post_desc']);
				// move image files
				$data['upload_image'] = $this->move_images($_FILES);
				$user_email = isset($user_data['user_data']['LOGIN_INFO']['email'])?$user_data['user_data']['LOGIN_INFO']['email']:$user_data['fe_email'];
				$user_id = isset($user_data['user_data']['LOGIN_INFO']['id'])?$user_data['user_data']['LOGIN_INFO']['id']:$user_data['fe_user_id'];
				$data['user_id'] = $user_id;
				if($this->post_model->save_fe_post($data,$user_id)){
					$return['status_code'] = 1;
					//$return['msg'] = '上傳成功！還要請您稍侯片刻，好俬迷會立即審查您的分享';
					$return['msg'] = '上傳成功！請至【我的收藏】查看您的分享';
					$this->_send_email('user_upload_idea',$user_email,$data);
				}
				else{
					$return['status_code'] = 4;
					$return['msg'] = '上傳失敗，請洽網站管理員或稍候再試';
				}
			}
			
		}
		else{
			$data['category'] = $this->config->item('category', 'layout');

			if(!in_array($data['post_category'], $data['category'])){
				$return['status_code'] = 2;
				$return['msg'] = '請選擇欲分享類別';
				
			}elseif(!isset($_FILES['upload_image']['name'][0])){
				$return['status_code'] = 2;
				$return['msg'] = '請至少上傳一張圖片';
				
			}elseif(validation_errors() != false){
				$return['status_code'] = 3;		
			}
		}

		$return['html'] = $this->load->view('houseme/upload_idea_form', $data, true);
		echo json_encode($return);

	}

	function uploadIdeaWithName(){
		
		$data = array();
		$return = array();
		$user_data = $this->user_data;
		//echo "<pre>";print_r($user_data);echo "</pre>";exit;
		//echo "<pre>";print_r($_FILES);echo "</pre>";exit;
		$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
		$data['category'] = $this->config->item('category', 'layout');

		$this->form_validation->set_rules('post_username', 'post user name', 'trim|required|xss_clean');
		$this->form_validation->set_rules('post_excerpt', 'post excerpt', 'trim|required|xss_clean');
		$this->form_validation->set_rules('post_desc', 'post desc', 'trim|required|xss_clean');

		if ($this->form_validation->run()) {

			if(!isset($_FILES['upload_image']['name'][0])){
				$return['status_code'] = 2;
				$return['msg'] = '請至少上傳一張圖片';
				$return['html'] = $this->load->view('houseme/upload_idea_form_with_name', $data, true);
				echo json_encode($return);exit;
				
			}
			elseif(!in_array($data['post_category'], $data['category'])){
				$return['status_code'] = 2;
				$return['msg'] = '請選擇欲分享類別';
				$return['html'] = $this->load->view('houseme/upload_idea_form_with_name', $data, true);
				echo json_encode($return);exit;

			}
			else{
				$allowedTypes = $this->config->item('allow_upload_image_type', 'layout');

				foreach ($_FILES['upload_image']['tmp_name'] as $key => $value) {
					$detectedType = exif_imagetype($value);
					if(!in_array($detectedType, $allowedTypes)){
						$return['status_code'] = 2;
						$return['msg'] = '檔案只允許圖片格式';
						$return['html'] = $this->load->view('houseme/upload_idea_form_with_name', $data, true);
						echo json_encode($return);exit;
					}
					else{// unset category element 不然insert 會有錯誤
						unset($data['category']);
					}
				}

				// get user id
				if(isset($user_data['user_data']['LOGIN_INFO']['id'])){
					$uid = $user_data['user_data']['LOGIN_INFO']['id'];
				}
				elseif(isset($user_data['fe_user_id'])){
					$uid = $user_data['fe_user_id'];
				}


				// update user name
				$update_status = $this->user_model->updateUserName($uid,$data['post_username']);
				
				if($update_status === true){
					$return['status_code'] = 1; // update successfully
					$return['msg'] = '更新成功';
					if($this->facebook->checkLoginStatus()){//fb already login

						$user_data['user_data']['LOGIN_INFO']['name'] = $data['post_username'];
						$this->session->set_userdata('user_data', $user_data['user_data']);
					}
					elseif($this->tank_auth->is_fe_logged_in()){
						$this->session->set_userdata('fe_username', $data['post_username']);
					}

					// unset 否則insert 到post table 時會發生錯誤
					unset($data['post_username']);

				}
				elseif($update_status === '2'){
					$return['status_code'] = 2; // username duplicate
					$return['msg'] = '重覆的使用者名稱，請使用另一個名稱';
					$return['html'] = $this->load->view('houseme/upload_idea_form_with_name', $data, true);
					echo json_encode($return);exit;
				}
				else{
					$return['status_code'] = 4; // update successfully
					$return['msg'] = '更新失敗，請稍候再試，或洽網站管理員';
					echo json_encode($return);exit;	
				}


				// check file type success!
				// replace \r\n to <br >
				
				$data['post_desc'] = nl2br($data['post_desc']);
				// move image files
				$data['upload_image'] = $this->move_images($_FILES);
				$user_email = isset($user_data['user_data']['LOGIN_INFO']['email'])?$user_data['user_data']['LOGIN_INFO']['email']:$user_data['fe_email'];
				$user_id = isset($user_data['user_data']['LOGIN_INFO']['id'])?$user_data['user_data']['LOGIN_INFO']['id']:$user_data['fe_user_id'];
				$data['user_id'] = $user_id;
				if($this->post_model->save_fe_post($data,$user_id)){
					$return['status_code'] = 1;
					//$return['msg'] = '上傳成功！還要請您稍侯片刻，好俬迷會立即審查您的分享';
					$return['msg'] = '上傳成功！請至【我的收藏】查看您的分享';
					$this->_send_email('user_upload_idea',$user_email,$data);
				}
				else{
					$return['status_code'] = 4;
					$return['msg'] = '上傳失敗，請洽網站管理員或稍候再試';
				}
			}
			
		}else{
			if(validation_errors() != false){
				$return['status_code'] = 3;	
			}
		}
		
		$return['html'] = $this->load->view('houseme/upload_idea_form_with_name', $data, true);
		echo json_encode($return);

	}

	function move_images($files) // move images from temp to original and thumbs directory // and clean temp
    {
    	$user_data = $this->user_data;
        $user_id = isset($user_data['user_data']['LOGIN_INFO']['id'])?$user_data['user_data']['LOGIN_INFO']['id']:$user_data['fe_user_id'];
        $user_email = isset($user_data['user_data']['LOGIN_INFO']['email'])?$user_data['user_data']['LOGIN_INFO']['email']:$user_data['fe_email'];

        
        $originalImageDirectory = $_SERVER["DOCUMENT_ROOT"].$this->config->item('image_uploader_fe_original', 'layout').$user_id.'/';
        $thumbsImageDirectory = $_SERVER["DOCUMENT_ROOT"].$this->config->item('image_uploader_fe_thumbs', 'layout').$user_id.'/';

        if (!is_writable($originalImageDirectory)){
            mkdir($originalImageDirectory);
        }
        
        if (!is_writable($thumbsImageDirectory)){
            mkdir($thumbsImageDirectory);
        }
        
        $file_data = array();

		if(isset($files['upload_image']) && !empty($files['upload_image'])){
			foreach ($files['upload_image']['tmp_name'] as $key => $value) {
				if(!empty($value)){
					
					$ext = pathinfo($files["upload_image"]["name"][$key], PATHINFO_EXTENSION);
					$filepath = strtotime('now').'.'.$ext;
					// move to original
					if(move_uploaded_file($files['upload_image']['tmp_name'][$key],$originalImageDirectory.$filepath)){
						// save to thumb
						sleep(1);
						$this->resizeImage($originalImageDirectory.$filepath,$thumbsImageDirectory.$filepath);
						// push to array: upload_image
						$file_data[] = $filepath;	
					}
				}
			}
		}
        
        return $file_data;
    }

    private function resizeImage($originalFileName,$thumbFileName){
        $t_width = 200; // Maximum thumbnail width
        $t_height = 150; // Maximum thumbnail height
        $construct = array('fileName'=>$originalFileName);
        //$this->load->library('Resize');

        // using normal require to load library
        // and new the class to prevent caching
        require_once(APPPATH.'libraries/Resize.php');
        $my_resize = new Resize($construct);
        $my_resize->resizeImage($t_width, $t_height, 0);
        $my_resize->saveImage($thumbFileName, 100);
    }

	function editCategoryName(){
		if($this->facebook->checkLoginStatus() || $this->tank_auth->is_fe_logged_in()){//fb already login
			$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
			$user_data = $this->user_data;
			
			if(isset($user_data['user_data']['LOGIN_INFO']['id'])){
				$uid = $user_data['user_data']['LOGIN_INFO']['id'];
			}
			elseif(isset($user_data['fe_user_id'])){
				$uid = $user_data['fe_user_id'];
			}
			$user_collects = $this->user_model->selectUserCollects($uid);
			$collects = $user_collects[0]['collects'];
			$collects = urldecode($collects);
			$collects = json_decode($collects);

			$collect_alias = $user_collects[0]['collect_alias'];
			$collect_alias = urldecode($collect_alias);
			$collect_alias = json_decode($collect_alias);

			$replace_array = array('/','(',')');
			$new_collect_alias = $data['new_category_name'];
			$new_category_name = str_replace($replace_array, '', $data['new_category_name']);
			$old_category_name = str_replace($replace_array, '', $data['old_category_name']);

			if(!isset($collects->$old_category_name)){
				$return['status_code'] = 2; // not find old category in db
				$return['msg'] = '原俬迷本名稱有誤，請重新整理頁面後再試';
			}
			else{
				
				$collects->$new_category_name = $collects->$old_category_name;
				unset($collects->$old_category_name);
				
				$collects = json_encode($collects);
				$collects = urlencode($collects);

				$collect_alias->$new_category_name = $new_collect_alias;
				unset($collect_alias->$old_category_name);

				$collect_alias = json_encode($collect_alias);
				$collect_alias = urlencode($collect_alias);


				if($this->user_model->changeCategoryName($uid,$collects,$collect_alias)){
					$return['status_code'] = 1;
					$return['msg'] = '變更成功！';
				}
				else{
					$return['status_code'] = 4; // not find category in db
					$return['msg'] = '收藏時發生錯誤，請連絡網站管理者或稍侯再試';
				}
			}
		}
		else{//fb not login
			$return['status_code'] = 3; // fb not login
			$return['msg'] = '請先登入';
		}

		
		echo json_encode($return);
	}
	function addCategory(){
		$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
		$return = array();
		if($this->facebook->checkLoginStatus() || $this->tank_auth->is_fe_logged_in()){//fb already login || email login
			if(!empty($data['new_category'])){
				$user_data = $this->user_data;
				if(isset($user_data['user_data']['LOGIN_INFO']['id'])){
					$uid = $user_data['user_data']['LOGIN_INFO']['id'];
				}
				elseif(isset($user_data['fe_user_id'])){
					$uid = $user_data['fe_user_id'];
				}
				$status_code = $this->user_model->insertNewCategory($uid,$data['new_category']);

				if($status_code == '1'){
					
					$return['status_code'] = 1; // insert successfully
					$return['html'] = '<li>'.$data['new_category'].'</li>';
					$return['msg'] = '新增成功';
				}
				elseif($status_code=='2'){
					$return['status_code'] = 2; // insert category error
					$return['msg'] = '新增分類發生錯誤，請連絡網站管理者';
				}
				elseif($status_code=='5'){
					$return['status_code'] = 5; // insert category error
					$return['msg'] = '分類重覆！';
				}
			}
			else{ // empty category
				$return['status_code'] = 4; // no category
				$return['msg'] = '請輸入分類名稱';
			}

		}
		else{ //fb not login
			$return['status_code'] = 3; // fb not login
			$return['msg'] = '請先登入';
		}

		

		echo json_encode($return);
	}

	function dateSort($a,$b){
		$dateA = strtotime($a['modified_time']);
		$dateB = strtotime($b['modified_time']);
		return (($dateA-$dateB)>0)?-1:1;
	}

	/**
	 * Send email message to frontend user
	 *
	 * @param	string
	 * @param	string
	 * @param	array
	 * @return	void
	 */
	function _send_email($type, $email, &$data)
	{
		$data['site_name'] = $this->config->item('website_name', 'tank_auth');
		$this->load->library('email');
		$this->email->from($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
		$this->email->reply_to($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
		$this->email->to($email);
		$this->email->subject(sprintf($this->lang->line('auth_subject_'.$type), $this->config->item('website_name', 'tank_auth')));
		$this->email->message($this->load->view('email/'.$type.'-html', $data, TRUE));
		$this->email->set_alt_message($this->load->view('email/'.$type.'-txt', $data, TRUE));
		$this->email->send();
	}
}

/* End of file houseme.php */
/* Location: ./application/controllers/houseme.php */